package com.fengzheng.basic.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fengzheng.basic.common.config.response.ResultBean;
import com.fengzheng.basic.common.config.response.ResultCodeMsg;
import com.fengzheng.basic.model.po.SysRolePo;
import com.fengzheng.basic.model.dto.SysRoleDto;
import com.fengzheng.basic.model.vo.SysRoleVo;
import com.fengzheng.basic.service.sys.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@RestController
@Validated
@RequestMapping("/api/sys/role")
public class SysRoleController {

    @Autowired
    private ISysRoleService sysRoleService;

    @PostMapping("/save")
    public ResultBean save(@Valid @RequestBody SysRoleDto sysRoleDto){
        Long id = sysRoleDto.getId();
        SysRolePo info = BeanUtil.copyProperties(sysRoleDto, SysRolePo.class);
        if(id==null){
            SysRolePo sysRolePo = sysRoleService.getOne(Wrappers.<SysRolePo>lambdaQuery().eq(SysRolePo::getName,info.getName()));
            if(sysRolePo==null){
                return new ResultBean(sysRoleService.save(info));
            }else{
                return new ResultBean(ResultCodeMsg.RoleExist);
            }
        }else{
            SysRolePo sysRolePo = sysRoleService.getOne(Wrappers.<SysRolePo>lambdaQuery().eq(SysRolePo::getId,id));
            if(sysRolePo==null){
                return new ResultBean(ResultCodeMsg.RoleNotExist);
            }else{
                return new ResultBean(sysRoleService.updateById(info));
            }
        }
    }

    @PostMapping("/delete/{id}")
    public ResultBean delete(@PathVariable Long id){
        if(sysRoleService.getById(id)==null){
            return new ResultBean(ResultCodeMsg.RoleNotExist);
        }
        return new ResultBean(sysRoleService.removeById(id));
    }

    @GetMapping("/find")
    public SysRoleVo find(@NotNull(message = "id不能为空") Long id){
        SysRolePo sysRolePo = sysRoleService.getOne(Wrappers.<SysRolePo>lambdaQuery().eq(SysRolePo::getId,id));
        SysRoleVo sysRoleVo = BeanUtil.copyProperties(sysRolePo, SysRoleVo.class);
        return sysRoleVo;
    }

}
